package com.scm.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.scm.model.Poitem;
import com.scm.util.DbUtil;

public class PoitemDao extends BaseDao<Poitem>{

	public PoitemDao(Connection conn) {
		super();
		this.conn = conn;
	}
	public PoitemDao(){
		
	}
	/**
	 * 新增采购单明细
	 * @param poitems
	 * @throws SQLException
	 */
	public int[] add(List<Poitem> poitems) throws SQLException{
		PreparedStatement ps = null;
		try{
			String sql = "insert into poitem values(?,?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			for(Poitem p:poitems){
				ps.setLong(1, p.getPoId());
				ps.setString(2, p.getProductCode());
				ps.setDouble(3, p.getUnitPrice());
				ps.setInt(4, p.getNum());
				ps.setString(5, p.getUnitName());
				ps.setDouble(6, p.getItemPrice());
				ps.addBatch();
			}
			return ps.executeBatch();
		}finally{
			DbUtil.close(null, null, ps);
		}
	}
	/**
	 * 根据采购单id删除详情表
	 * @param poid
	 * @return
	 * @throws SQLException
	 */
	public int deleteByPoid(long  poid) throws SQLException{
		PreparedStatement ps = null;
		try{
			String sql = "delete from poitem where poid =?";
			ps = conn.prepareStatement(sql);
			ps.setLong(1, poid);
			return ps.executeUpdate();
		}finally{
			DbUtil.close(null, null, ps);
		}
	}
	/**
	 * 根据主单id查询详细信息
	 * @param poid
	 * @return
	 * @throws SQLException
	 */
	public List<Poitem> selectByPoid(long poid) throws SQLException{
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Poitem> poitems = new ArrayList<Poitem>();
		conn = DbUtil.getConn();
		try{
			String sql = "select * from poitem p , product pr where pr.productcode=p.productcode and poid ="+poid;
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				Poitem item = new Poitem();
				item.setPoId(poid);
				item.setProductCode(rs.getString("productcode"));
				item.setNum(rs.getInt("num"));
				item.setProductName(rs.getString("name"));
				item.setUnitName(rs.getString("unitname"));
				item.setUnitPrice(rs.getDouble("unitprice"));
				poitems.add(item);
			}
		}finally{
			DbUtil.close(null, rs, ps);
		}
		return poitems;	
	}

	@Override
	public List<Poitem> selectData(Map<String, String> querymap) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int generateQueryCondition(Map<String, String> queryMap, Map<Integer, String> params, StringBuilder sql) {
		// TODO Auto-generated method stub
		return 0;
	}
}
